C++ analysis of Json [jsoncpp]

  • 2020-05-19 05:29:08
  • OfStack

The example in this article shows how C++ parses Json. I will share it with you for your reference as follows:

JSON(JavaScript Object Notation) is a lightweight data interchange format, similar to xml. This paper mainly records VS2008 using Jsoncpp to parse json.

Jsoncpp is a cross-platform open source libraries, download address: http: / / sourceforge net/projects/jsoncpp /, I download v0. 5.0, about 104 K package.

Method 1: use the lib file generated by Jsoncpp

Unzip the Jsoncpp file downloaded above and find jsoncpp.sln in the jsoncpp-src-0.5.0 /makefiles/vs71 directory. VS2008 is compiled with the VS2008 version and generates the static link library by default. For project reference, simply include the header file under include/json and the generated.lib file.

How to include lib file: in.cpp file #pragma comment(lib." json_vc71_libmt.lib "), write lib file name in Input Dependencies under Linker in Input project properties (json_vc71_libmt.lib, Debug json_vc71_libmtd.lib)

Note: the lib project build option for Jsoncpp should be 1 to the VS project build option. If the project compilation option of lib is MT (or MTd), MT (or MTd) should also be selected in VS project, otherwise there will be compilation errors. debug and release generate different names of lib files, be careful not to read it wrong and use it as one file (I made this mistake).

Method 2: use the.cpp and.h files in the Jsoncpp package

Unzip the Jsoncpp file downloaded above, copy the jsoncpp-src-0.5.0 file into the project directory, and include the jsoncpp-src-jsoncpp-src-0.5.0 \include\ jsoncpp-src-0.5.0 \ jsoncpp-src-0.5.0 \src\lib_json files into the VS project. Additional Include Directories contains the header directory under C/C++ properties of VS project.\ jsoncpp-src-0.5.0 \include. Include the json header in the cpp file you are using, e.g. #include "json/ json.h ". Set the Precompiled Header property of json_reader.cpp, json_value.cpp3 files to Not Using Precompiled Headers, otherwise there will be an error in the compilation.

jsoncpp USES elaboration

jsoncpp mainly includes three types of class: Value, Reader and Writer. All object and class names in jsoncpp are in namespace Json, including json.h.
Json::Value can only handle strings of type ANSI. If the C++ program is encoded in Unicode, it is better to add one Adapt class.

Here's a code example from the web:

1. Parse json from a string


const char* str = "{\"uploadid\": \"UP000000\",\"code\": 100,\"msg\": \"\",\"files\": \"\"}";
Json::Reader reader;
Json::Value root;
if (reader.parse(str, root)) // reader will Json String parsing to root . root Will contain Json All the child elements in 
{
  std::string upload_id = root["uploadid"].asString(); //  Access node, upload_id = "UP000000"
  int code = root["code"].asInt();  //  Access node, code = 100
}

2. Parse json from the file


int ReadJsonFromFile(const char* filename)
{
  Json::Reader reader;//  parsing json with Json::Reader
  Json::Value root; // Json::Value is 1 A very important type that can represent any type. Such as int, string, object, array
  std::ifstream is;
  is.open (filename, std::ios::binary );
  if (reader.parse(is, root, FALSE))
  {
    std::string code;
    if (!root["files"].isNull()) //  Access node, Access an object value by name, create a null member if it does not exist.
      code = root["uploadid"].asString();
    code = root.get("uploadid", "null").asString();//  Access node, Return the member named key if it exist, defaultValue otherwise.
    int file_size = root["files"].size(); //  get "files" The number of arrays 
    for(int i = 0; i < file_size; ++i) //  Through the array 
    {
      Json::Value val_image = root["files"][i]["images"];
      int image_size = val_image.size();
      for(int j = 0; j < image_size; ++j)
      {
        std::string type = val_image[j]["type"].asString();
        std::string url = val_image[j]["url"].asString();
        printf("type : %s, url : %s \n", type.c_str(), url.c_str());
      }
    }
  }
  is.close();
  return 0;
}

3. Insert json into the file


void WriteJsonData(const char* filename)
{
  Json::Reader reader;
  Json::Value root; // Json::Value is 1 A very important type that can represent any type. Such as int, string, object, array
  std::ifstream is;
  is.open (filename, std::ios::binary );
  if (reader.parse(is, root))
  {
    Json::Value arrayObj;  //  Build the object 
    Json::Value new_item, new_item1;
    new_item["date"] = "2011-11-11";
    new_item1["time"] = "11:11:11";
    arrayObj.append(new_item); //  Insert array member 
    arrayObj.append(new_item1); //  Insert array member 
    int file_size = root["files"].size();
    for(int i = 0; i < file_size; ++i)
      root["files"][i]["exifs"] = arrayObj;  //  Insert the original json In the 
    std::string out = root.toStyledString();
    //  Output unformatted json string 
    Json::FastWriter writer;
    std::string strWrite = writer.write(root);
    std::ofstream ofs;
    ofs.open("test_write.json");
    ofs << strWrite;
    ofs.close();
  }
  is.close();
}

Note: improper trial of Json will cause the program to crash


Json::Value root;
Json::Reader reader;

It is best to use the main function as a variable, not as a global variable, and not declare it multiple times (i.e., not in a loop or in another function). Because of its static property, it is destructed at the end of the first use, and later USES will access the invalid address.

json_value. cpp


Value::~Value() {
 switch (type_) {
 case nullValue:
 case intValue:
 case uintValue:
 case realValue:
 case booleanValue:
  break;
 case stringValue:
  if (allocated_)
   releaseStringValue(value_.string_);
  break;
 case arrayValue:
 case objectValue:
  delete value_.map_;//!!!!!!
  break;
 default:
  JSON_ASSERT_UNREACHABLE;
 }

The correct way to use it is as follows:


int getRebalancing(string str, Json::Value root, Json::Reader reader) ;
int main() {
  Json::Value root;
  Json::Reader reader;
  while(1){
    getRebalancing(string::str, root, reader);
    //do something
    }
  return 0;
}

PS: here are some useful json online tools for your reference:

Online JSON code validation, validation, beautification, formatting tools:
http://tools.ofstack.com/code/json

JSON online formatting tool:
http://tools.ofstack.com/code/jsonformat

Online XML/JSON interconversion tool:
http://tools.ofstack.com/code/xmljson

json code online formatting/beautification/compression/editing/conversion tools:
http://tools.ofstack.com/code/jsoncodeformat

C language style /HTML/CSS/json code formatting beautification tool:
http://tools.ofstack.com/code/ccode_html_css_json

I hope this article is helpful to you C++ programming.


Related articles: